﻿<?php
/**----------------------------------------------------+
 * 解析XML文件生成器
 * 读取XML文件，根据指定的模板文档，将XML中的数据结合模板转换为ERL文件
 * @author zhongkj@jieyou.cn
 +-----------------------------------------------------*/
//执行方法：php convert.php 数据类型
//例如：php convert.php map
error_reporting(E_ALL ^E_NOTICE);
$input_file = isset($argv[1]) ? $argv[1] : '';
$data_file_name = $input_file;
$tpl_file_name = $input_file;
$target_file_name = $input_file;
$cli_tpl_file_name = $input_file;
$cli_target_file_name = $input_file;
$attr_lable = require 'include/property.php';

define('ROOT',          str_replace('\\', '/', realpath(dirname(__FILE__))));
define('DATA_DIR',      ROOT.'/data/');
define('TPL_DIR',       ROOT.'/tpl/');
define('TARGET_DIR',    ROOT.'/target/');
define('CLIENT_CONFIG_DIR',str_replace('\\', '/',realpath(dirname(dirname(dirname(__FILE__))))).'/resources/res');

main($input_file, $data_file_name, $tpl_file_name, $target_file_name, $cli_tpl_file_name, $cli_target_file_name);
function main($input_file, $data_file_name, $tpl_file_name, $target_file_name, $cli_tpl_file_name, $cli_target_file_name){
    $data_file = DATA_DIR.$data_file_name.".xml";    
    $tpl_file = TPL_DIR.convert_dir.".tpl.php";    
    $target_file = TARGET_DIR.$target_file_name.".txt";    
       
	if($data_file ==""){
        exit("Error：Data files is empty!\n");
    }
    if (!file_exists(realpath($data_file))){
        exit("Error：Data file does not exist!\n".$data_file."\n");
    }
    
    //获取Excel生成的XML文件的数据
    $arrData = rdExcel_XML(realpath($data_file));
    //转换服务端数据
    if (file_exists(realpath($tpl_file))){
        echo ">> Please wait,server data {$tpl_file_name} is converted...\n";
        //解析服务端模板
	    $potoServer = parseTemplate($tpl_file,$arrData);	    
	    //写入文件保存服务端数据
	    writeFile($target_file, $potoServer);
	    echo ">> Convert server data {$tpl_file_name} is completed.\n";
    }	
    
}

//读取Excel生成的XML文件，返回数组
//Excel生成的XML文件数据的我们需要的结构为：
//Worksheet->Table->Row->Cell->Data
function rdExcel_XML($data_file){	
    $doc = new DOMDocument('1.0', 'gb2312');
    $doc->load( $data_file );

    $worksheets = $doc->getElementsByTagName("Worksheet");
    $isheet = 0;
    foreach( $worksheets as $worksheet ){
        $worksheet_ssname = $worksheet->getAttribute('ss:Name');
        $start_ss_name = substr($worksheet_ssname, 0, 4);
        if($start_ss_name == "DATA"){
            $tables = $worksheet->getElementsByTagName("Table");
            foreach( $tables as $table )
            {
                $rows = $table->getElementsByTagName("Row");
                $irow = '';
                $irows = get_row_id($rows);
                foreach( $rows as $row ){
                    $cells = $row->getElementsByTagName("Cell");
                    $icell = 0;
                    $icell_index = 0;
                    $icell_offset=0;
                    foreach( $cells as $cell ){
                        $icell = $irows[$icell_index];
                        $cell_ssindex = $cell->getAttribute('ss:Index');
                        if($cell_ssindex== ""){
                            $datas = $cell->getElementsByTagName("Data");
                            $data = $datas->item(0)->nodeValue;
                            $xml_data[$isheet][$irow][$icell]=$data; //将数据存储到3维数组里
                            //echo ">>$isheet $irow $icell $data<<\n";
                            ++$icell_index;
                        }else{
                            for($icell_index;$icell_index < $cell_ssindex;$icell_index++){
                                if($icell_index != $cell_ssindex-1 ){
                                    $data = "";
                                }else{
                                    $datas = $cell->getElementsByTagName( "Data" );
                                    $data = $datas->item(0)->nodeValue;
                                }
                                $icell = $irows[$icell_index];
                                // echo ">>$isheet $irow $icell $data<<\n";
                                $xml_data[$isheet][$irow][$icell]=$data;
                            }
                        }
                        //echo "\n";
                    }
//                    echo $isheet."\n";
                    ++$irow;
                }
            }
            ++$isheet;
        }
    }
    
    // $xml_data[SheetIndex][RowIndex][CellIndex]
    // 去除多余空行
    /*for ($i = 0; $i < sizeof($xml_data); $i++) {
    	$xj = 0;
    	for ($j = 0; $j < sizeof($xml_data[$i]); $j++) { // sheet
	    	if (!is_line_empty($xml_data[$i][$j])) {
	    		for ($k = 0; $k < sizeof($xml_data[$i][$j]); $k++) { // row
	    			$xml_new[$i][$xj][$k] = $xml_data[$i][$xj][$k];
	    		}
	    		++$xj;
	    	}
    	}
    }
    return $xml_new;
     */
    return $xml_data;
}	

/**
 * 打印指定变量的内容(用于调试)
 * @param mixd $var 变量名
 * @param string $label 标签名
 */
function dump($var, $label = null){
    $content .= print_r($var, true);
    echo $content;
}

// 解析标识行，获得标识
function get_row_id($rows){
    $cells = $rows->item(1)->getElementsByTagName("Cell");
    $icell = 0;
    $icell_offset=0;
    foreach( $cells as $cell ){
        $cell_ssindex = $cell->getAttribute('ss:Index');
        if($cell_ssindex== ""){
            $datas = $cell->getElementsByTagName("Data");
            $data = $datas->item(0)->nodeValue;
            //                            echo ">>$isheet $irow $data<<\t";
            $rowsid[$icell]=$data; //将数据存储到3维数组里
            ++$icell;
        }else{
            for($icell;$icell < $cell_ssindex;$icell++){
                if($icell != $cell_ssindex-1 ){
                    $data = "";
                }else{
                    $datas = $cell->getElementsByTagName( "Data" );
                    $data = $datas->item(0)->nodeValue;
                }
                $rowsid[$icell]=$data;
            }
        }
        //echo "\n";
    }
    return $rowsid;
}

//根据模板文件生成目标文件的内容
function parseTemplate($tpl_file, $xml_data, $count=0){
    ob_start();
    //extract($xml_data);
    include $tpl_file;
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}
//写文件
function writeFile($target_file, $content, $mode='wb'){
    $oldMask= umask(0);
    $fp = @fopen($target_file, $mode);
    fwrite($fp, $content);
    fclose($fp);
    umask($oldMask);
}

function pack_str($str){
    //如果是gbk,要转成utf8
    // $str = iconv('gbk','utf-8',$str);
    $utflen = strlen($str);
    if ($utflen > 65535) die('too long');
    $in .= pack('C2',$utflen>>8,$utflen>>0);
    return $in.$str;
}

//把类似于 0:固定 的数据取出0
function get_number($input){
    return substr($input, 0, strpos($input,":"));
}

//把类似于 0:固定 的字符取出
function get_string($input){
    return substr($input, strpos($input,":")+1);
}

// 判断是否为空行
// 如果一行的数据都为空行，即视为空行，否则为不空行
function is_line_empty($row_data) {
	for($i = 0; $i < sizeof($row_data); $i++){
        if($row_data[$i] != ""){
            return false;
        }
    }
    return true;
}

//检查列的数值是否为空
function check_num($number) {
	if ($number == "") return 0;
	else return $number;
}

//检查列的字符是否为空
function check_string($string) {
	if ($string == "") return '';
	else return $string;
}

//获取单元格中以换行分隔的元组数据组合为列表
function tupletolist($data){
	$arr_attr = explode("\n",$data);
    $output="";
    for($i = 0; $i < sizeof($arr_attr); $i++){
        if((trim($arr_attr[$i]))!=""){
        	$output .= $arr_attr[$i].',';
        }
    }
    $output = substr($output, 0, strlen($output)-1);
    return $output;
}

function attr_to_int($string){
    global $attr_lable;
    $len = count($attr_lable);
    $lable = array();
    $int = array();
    for ($i = 0; $i < $len; $i++)
    {
        $lable[$i] = $attr_lable[$i][0];
        $int[$i] = $attr_lable[$i][1];
    }

	if (!isset($lable) || !isset($int)){
		echo '策划-服务端-客户端 属性对应关系配置文件数据不存在，请检查后重试！';
		exit();
	}
	if (count($lable) != count($int)){
		echo '策划-服务端-客户端 属性对应关系配置文件数据不匹配，请检查后重试！';
		exit();
	}
    return str_replace($lable, $int, $string);
}

function get_count($rows, $index){
    $count = 0;
    for($i = 2; $i< sizeof($rows); $i++){
        if($rows[$i][$index] != "")
            $count = $count + 1;
    }
    return $count;
}

//数据转换 hp_max->hpMax
function attrName_conver($str){
	$idx = strpos($str,"_");
	//echo '<'.$str;
	if($idx !== "")
	{
		do
		{
			$w = substr($str, $idx+1, 1);
			//echo 'w==='.$w.'|';
			$bw = strtoupper($w);
			//echo 'bw==='.$bw.'|';
			$str = str_replace('_'.$w,$bw,$str);
			//echo 'str==='.$str.'|';
			$idx = strpos($str,"_");
			//echo 'idx==='.$idx.'|';
		}
		while($idx === "");
	}
	$str = str_replace('anti_poison','antiPoison',$str);
	$str = str_replace('anti_silent','antiSilent',$str);
	$str = str_replace('anti_speed,','antiSpeed,',$str);
	$str = str_replace('anti_stone','antiStone',$str);
	$str = str_replace('anti_stun','antiStun',$str);
	//echo '>}}}}'.substr('{anti_silent,20}', 6, 1).'????????';
	//echo $str;
	return $str;
}

// 转换获益数据
function gen_gain($gainStr){
    $list = explode("\n", $gainStr);
    $gains = "";
    foreach($list as $item){
        $item2 = substr(trim($item), 1, -1);
        $itemList = explode(",", $item2);
        if(sizeof($itemList) == 2){
            $gains = $gains. ", ?GAIN(". trim($itemList[0]). ", ". trim($itemList[1]). ")";
        }else if(sizeof($itemList) == 3){
            $gains = $gains. ", ?GAIN(item, ". $item. ")";
        }
    }
    return "[". substr($gains, 1). "]";
}


